package com.srwl.mytx.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.domain.Advertisement;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Coupon;
import com.srwl.mytx.domain.LiveRecord;
import com.srwl.mytx.domain.LiveRoom;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.Mulct;
import com.srwl.mytx.domain.Orders;
import com.srwl.mytx.domain.Reward;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.fragment.RedPacketDialogFragment;
import com.srwl.mytx.fragment.SendMultiplePacketDialog;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.LiveService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.PayUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.LiveCountDownView;
import com.srwl.mytx.widget.OfferDialog;
import com.srwl.mytx.widget.PresentDialog;
import com.srwl.mytx.widget.StopLiveDialog;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.srwl.mytx.adapter.OrderRecordAdapter.REQUEST_CODE_OFFER;


//import io.agora.rtc.Constants;
//import io.agora.rtc.RtcEngine;


public class LiveAudienceActivity extends LiveBaseActivity implements PresentDialog.InteractionListener, LiveCountDownView.InteractionListener {

    Context context;
    private final int msgViewHeight = 175;

    @BindView(R.id.live_start_countdown)
    TextView tv_countdownView;
    /* @BindView(R.id.img_icon)
     ImageView iv_anchorIcon;*/
   /* @BindView(R.id.tv_anchor_nick)
    TextView tv_anchorName;*/
    @BindView(R.id.iv_live_room_idle)
    ImageView iv_liveRoomIdle;
    @BindView(R.id.tv_bind_goods_name)
    TextView tv_bindGoodsName;
    @BindView(R.id.present_image)
    ImageView iv_present;
    @BindView(R.id.iv_pass)
    ImageView iv_pass;
    //-------------------------------------
    @BindView(R.id.btn_start)
    Button startBtn;
    @BindView(R.id.iv_switch_light)
    ImageView iv_lightSwitch;
    @BindView(R.id.iv_switch_voice)
    ImageView iv_voiceSwitch;
    @BindView(R.id.iv_switch_camera)
    ImageView iv_cameraSwitch;
    @BindView(R.id.img_bt_close)
    ImageButton closeLive;

    private PresentDialog dialog;
    private Thread countDownThread;
    private long lastClickTime = 0;
    private int countDown;
    //private PresentFragment presentFragment;
    private Handler handler = new Handler();

    private boolean isEmpty;


    private Runnable countDownRunnable = new Runnable() {
        @Override
        public void run() {
            if (countDown > 0) {
                handler.postDelayed(countDownRunnable, 1000);
                handleUpdateCountdown();
                countDown--;
            } else {

                startLive();
            }
        }
    };

    @Override
    protected void onActivityCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_live_audience);
        ButterKnife.bind(this);
        context = this;
        isAnchor = false;
        countDownView.setListener(this);
        //观众端不打开音频
        //mRtcEngine.disableAudio();
        //设置直播间角色 ，true是代表观众，false代表主播
        // setClientRole(Constants.CLIENT_ROLE_AUDIENCE);
        //  joinChannel(liveRoom.getId());

        /***
         *  从服务端加载礼物信息
         *
         *  启动要同时修改  PresentRecyclerViewAdapter 的onBindViewHolder方法
         *                   以及LiveLeftGiftView的setReward方法
         */

        //initData();
        initLocalData();
        //加载头像
        // Glide.with(this).load(liveRoom.getCover()).diskCacheStrategy(DiskCacheStrategy.ALL).into(coverView);
        GlideLoadUtils.glideLoad(this, liveRoom.getCover(), coverView);

        initGoodsList();
        initClickListener();
        //对直播间状态进行查询
        queryLiveRoomStatus();

        setOnLiveStatusChangeListener(new LiveStatusListener() {
            @Override
            public void onAnchorJoin() {
                //查询直播间的信息
                // queryLiveRoomStatus(false); 现在更从这儿去查询，根据服务端推送的直播开始的消息中，拿到直播开始相关数据了，
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        readyLiveChangeUiForAudience();
                    }
                });
            }

            @Override
            public void prepareStartLive() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        hideLiveRoomIdleView();
                        //  countDownView.startCount(liveRecord.getDuration(), liveRecord.getCreated().getTime());
                        //  rv_audienceList.showAnchorAvatar();
                        showRewardAndMulctView();
                    }
                });
                audienceList.remove(anchor);
                refreshGoodsList(anchor.getuId());
            }

            @Override
            public void startLive() {


                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        startLiveChangeUiForAudience();
                    }
                });

            }

            @Override
            public void onAnchorLeave() {
                resetLiveRoom();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //   stopLiveChangeUiForAudience();
                        //当主播关闭直播的时候，删除远程视频view，
                        removeVideoView();
                    }
                });
            }

            @Override
            public void stopLive() {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        stopLiveChangeUiForAudience();
                    }
                });
                anchor = null;
                if (goodsList != null) {
                    goodsList.clear();
                }

                goodsDateChange();
            }


            @Override
            public void timeOut() {

            }
        });

    }

    private void initClickListener() {
        iv_liveRoomIdle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //避免重复点击
                long currentTime = System.currentTimeMillis();
                if (currentTime - lastClickTime < 1000) {
                    return;
                }
                lastClickTime = currentTime;
                //直播准备，更新服务端的直播间状态，新建并保存一个直播记录到数据库
                prepareLive();


            }
        });
        startBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.removeCallbacks(countDownRunnable);
                startLive();
            }
        });
        iv_voiceSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (iv_voiceSwitch.isSelected()) {
//                    iv_voiceSwitch.setSelected(false);
//                    mRtcEngine.muteLocalAudioStream(false);
//                } else {
//                    iv_voiceSwitch.setSelected(true);
//                    mRtcEngine.muteLocalAudioStream(true);
//                }
            }
        });
        iv_cameraSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //切换摄像头
                // mRtcEngine.switchCamera();
                if (iv_cameraSwitch.isSelected()) {
                    iv_cameraSwitch.setSelected(false);
                } else {
                    iv_cameraSwitch.setSelected(true);
                }
            }
        });

        iv_lightSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (iv_lightSwitch.isSelected()) {
                    iv_lightSwitch.setSelected(false);
                    // mRtcEngine.setCameraTorchOn(false);
                } else {
                    iv_lightSwitch.setSelected(true);
                    //  mRtcEngine.setCameraTorchOn(true);
                }
            }
        });
        iv_redPacket.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAnchor) {

                    SendMultiplePacketDialog sendMultiplePacketFragment = SendMultiplePacketDialog.newInstance(liveRoom.getId(), null);
                    sendMultiplePacketFragment.show(getSupportFragmentManager(), "");
                    sendMultiplePacketFragment.setListener(new SendMultiplePacketDialog.InteractionListener() {
                        @Override
                        public void onSendCouponSuccess(Coupon coupon) {
                            notifySendMultipleCoinCoupon(coupon);
                            LiveAudienceActivity.this.showToast("发送红包完成");
                            hideSoftKeyboard();


                        }

                        @Override
                        public void showToast(String message) {

                        }
                    });
                } else {
                    openCoupon();
                    iv_redPacket.setImageResource(R.drawable.tx_live_red_packet_open);
                    if (couponList.size() > 1) {
                        /*if (couponList.size()==2){
                            tv_red_Packet_Num.setVisibility(View.INVISIBLE);
                        }*/
                        tv_red_Packet_Num.setText(couponList.size() - 1 + "");
                    } else if (couponList.size() == 1) {
                        tv_red_Packet_Num.setVisibility(View.INVISIBLE);
                    }

                    //tv_red_Packet_Num.setVisibility(View.VISIBLE);

                }
                iv_redPacket.clearAnimation();
            }
        });
    }

    private void openCoupon() {

        //如果红包类型是子红包，说明已经领取成功了
        if (childCoupon != null) {
            Intent intent = new Intent(LiveAudienceActivity.this, MultipleCouponDetailActivity.class);
            intent.putExtra(Constant.EXTRA_INFO_CHILD_COUPON, childCoupon);

            startActivity(intent);
            //couponView.clearAnimation();
            return;

        }
        if (couponList == null || couponList.size() == 0) {
            return;
        }
        Coupon coupon = couponList.get(0);

        if (coupon == null) {

            return;
        }
        if (TextUtils.equals(coupon.getuId(), myUserInfo.getuId())) {//如果是自己，直接进入详情，自己不能领取自己发的红包
            Intent intent = new Intent(LiveAudienceActivity.this, MultipleCouponDetailActivity.class);
            intent.putExtra(Constant.EXTRA_INFO_COUPON, coupon);
            startActivity(intent);

        } else {

            RedPacketDialogFragment redPacketDialogFragment = RedPacketDialogFragment.newInstance(coupon);
            redPacketDialogFragment.show(getSupportFragmentManager(), "RedPacketDialogFragment");
            redPacketDialogFragment.setOnFragmentInteractionListener(new RedPacketDialogFragment.OnFragmentInteractionListener() {
                @Override
                public void onReceiveCouponComplete(Coupon childCoupon, boolean isEmpty) {
                    //TODO : 直接将第一个红包替换成子红包会丢失状态 无法判断红包是否领完  因此在领取红包时候由服务端添加一个isEmpty来判断红包是否领完

                    LiveAudienceActivity.this.childCoupon = childCoupon;

                    if (isEmpty) {
                        if (couponList.size() == 1) {
                            iv_redPacket.clearAnimation();
                            iv_redPacket.setImageResource(R.drawable.tx_live_red_packet_open);

                        }
                        LiveAudienceActivity.this.isEmpty = isEmpty;
                        couponEmpty(coupon);
                        //couponList.remove(0);
                        //couponList.remove(1);
                        // coupon = childCoupon;//接收成功返回的是 子红包
                    }

                    //couponList.add(0,childCoupon);
                    // coupon = childCoupon;//接收成功返回的是 子红包
                   /* //停止红包动画
                    couponView.clearAnimation();
                    couponView.setImageResource(R.drawable.tx_live_red_packet_open);
*/

                }


                @Override
                public void onStatusChange(Integer status) {
                    coupon.setStatus(status);
                }

                @Override
                public void onCouponExpire(Coupon coupon) {

                }
            });
        }
    }

    private void prepareLive() {
        progressBar.setVisibility(View.VISIBLE);
        LiveRoom updateLiveRoom = new LiveRoom();
        updateLiveRoom.setId(liveRoom.getId());

        isAnchor = true;
        RetrofitManager.getInstance().createRequest(LiveService.class)
                .startLive(updateLiveRoom)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "开始直播错误:" + response.code());
                            isAnchor = false;
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "开始直播错误:" + result.getMsg());
                            isAnchor = false;
                            switch (result.getStatus()) {

                                case Constant.LIVE_ROOM_HAD_STARTED:
                                    showToast(iv_liveRoomIdle, "手慢了一点，别人已经开始直播了");
                                    return;
                            }

                            return;
                        }

                        Log.d(TAG, "开始直播:更新服务端完成");


                        //设置角色为主播，开始直播is
                        JSONObject data = (JSONObject) result.getData();
                        liveRecord = data.toJavaObject(LiveRecord.class);


                        //发送通知信息到直播间，开始直播

                        notifyStartLive(liveRecord);


                        //  countDownView.startCount(liveRecord.getDuration(), liveRecord.getCreated().getTime());
                        // setClientRole(Constants.CLIENT_ROLE_BROADCASTER);
                        //暂停发送本地视频流
                        //  mRtcEngine.muteLocalAudioStream(true);
                        // mRtcEngine.muteLocalVideoStream(true);
                        //开始5s倒计时,倒计时结束都没有手动点开始，自动开始
                        countDown = COUNTDOWN_START_INDEX;
                        handler.post(countDownRunnable);
//                        countDownThread = new Thread() {
//                            public void run() {
//                                int i = COUNTDOWN_START_INDEX;
//                                do {
//                                    final int finalI = i;
//                                    runOnUiThread(new Runnable() {
//                                        @Override
//                                        public void run() {
//
//                                            handleUpdateCountdown(finalI);
//                                        }
//                                    });
//                                    i--;
//                                    try {
//                                        Thread.sleep(COUNTDOWN_DELAY);
//                                    } catch (InterruptedException e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                                while (!isLiveStarted && i >= COUNTDOWN_END_INDEX);
//                            }
//                        };
//                        countDownThread.start();


                        // if (surfaceViewLocal == null) {
                        //设置本地视频
                        setLocalVideo();

                        //    }
//                                        else {
//                                            //判断容器中的是否是本地视频view,如果不是，则清空容器，重新添加本地视频view
//                                            if (rl_videoContainer.getChildCount() != 0 && !TextUtils.equals((String) rl_videoContainer.getChildAt(0).getTag(), "local")) {
//                                                rl_videoContainer.removeAllViews();
//                                                rl_videoContainer.addView(surfaceViewLocal);
//                                            }
//                                        }
                        //更改ui 把直播需要的按键，显示出来，隐藏coverView等
                        startLiveChangeUIForAnchor();

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        isAnchor = false;
                    }
                });
    }

    /**
     * app端 通知直播间，开始直播
     *
     * @param liveRecord
     */
    private void notifyStartLive(LiveRecord liveRecord) {
        Message message = new Message();
        LiveRoom startLiveInfo = new LiveRoom();
        startLiveInfo.setLiveRecord(liveRecord);
        User anchor = new User();
        anchor.setuId(myUserInfo.getuId());
        anchor.setAvatar(myUserInfo.getAvatar());
        anchor.setUsername(myUserInfo.getUsername());
        startLiveInfo.setAnchor(anchor);
        JSONObject data = new JSONObject();
        data.put("liveRoom", startLiveInfo);
        message.setExtraData(data.toJSONString());
        message.setType(Constant.LIVE_ROOM_PUSH_MESSAGE_LIVE_START);
        //MyApplication.getInstance().getmAgoraAPI().messageChannelSend(liveRoom.getId(), JSONObject.toJSONString(message), "");
    }


    /**
     * app端 通知直播间，结束直播
     */
    private void notifyStopLive() {
        Message message = new Message();
        message.setType(Constant.LIVE_ROOM_PUSH_MESSAGE_LIVE_STOP);
        // MyApplication.getInstance().getmAgoraAPI().messageChannelSend(liveRoom.getId(), JSONObject.toJSONString(message), "");
    }

    /**
     * app端 通知直播间，有打赏
     */
    private void notifyReward(Reward reward, int duration) {
        Message message = new Message();
        message.setType(Constant.LIVE_ROOM_PUSH_MESSAGE_RECEIVED_REWARD);
        JSONObject data = new JSONObject();
        data.put("reward", reward);
        data.put("duration", duration);
        message.setExtraData(data.toJSONString());
        // MyApplication.getInstance().getmAgoraAPI().messageChannelSend(liveRoom.getId(), JSONObject.toJSONString(message), "");
    }


    /**
     * app端 通知直播间，有 点踩
     */
    private void notifyMulct(Mulct mulct, int duration) {
        Message message = new Message();
        message.setType(Constant.LIVE_ROOM_PUSH_MESSAGE_RECEIVED_MULCT);
        JSONObject data = new JSONObject();
        data.put("reward", mulct);
        data.put("duration", duration);
        message.setExtraData(data.toJSONString());
        //MyApplication.getInstance().getmAgoraAPI().messageChannelSend(liveRoom.getId(), JSONObject.toJSONString(message), "");
    }

    /**
     * 通知 发出红包领完
     */
    private void couponEmpty(Coupon coupon) {
        Message message = new Message();
        message.setType(Constant.LIVE_ROOM_PUSH_MESSAGE_RECEIVED_COUPON_WAS_EMPTY);
        JSONObject data = new JSONObject();
        data.put("coupon", coupon);

        message.setExtraData(data.toJSONString());
        // MyApplication.getInstance().getmAgoraAPI().messageChannelSend(liveRoom.getId(), JSONObject.toJSONString(message), "");


    }


    /**
     * 通知 发出了一对多红包
     */
    private void notifySendMultipleCoinCoupon(Coupon coupon) {

        Message message = new Message();
        message.setType(Constant.LIVE_ROOM_PUSH_MESSAGE_RECEIVED_FUND_COUPON);
        JSONObject data = new JSONObject();
        data.put("coupon", coupon);
        coupon.setTargetUser(anchor);//当前主播就是自己，也可以获取当前登录用户信息丢进去
        message.setExtraData(data.toJSONString());
        // MyApplication.getInstance().getmAgoraAPI().messageChannelSend(liveRoom.getId(), JSONObject.toJSONString(message), "");


    }

    /**
     * app端 通知直播间，有 出价
     */
    private void notifyOffer(Orders orders) {
        Message message = new Message();
        message.setType(Constant.LIVE_ROOM_PUSH_MESSAGE_RECEIVED_OFFER);
        JSONObject data = new JSONObject();
        data.put("orders", orders);
        message.setExtraData(data.toJSONString());
        // MyApplication.getInstance().getmAgoraAPI().messageChannelSend(liveRoom.getId(), JSONObject.toJSONString(message), "");
    }


    /**
     * 如果在直播中，就退出直播，如果没有，就退出频道
     */
    @OnClick(R.id.img_bt_close)
    void close() {

        if (isAnchor) {
            stopLiveToService();

        } else {
            finish();
        }


    }

    private void stopLiveToService() {
//            liveRoom.setanchorId(UserProfileManager.getInstance().getLoginUserInfo().getuId());
//            liveRoom.setrId(liveRecord.getId());
        LiveRoom newLiveRoom = new LiveRoom();
        newLiveRoom.setId(liveRoom.getId());
        newLiveRoom.setrId(liveRecord.getId());
        newLiveRoom.setanchorId(myUserInfo.getuId());
        RetrofitManager.getInstance().createRequest(LiveService.class)
                .stopLive(newLiveRoom)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "停止直播出错:" + response.code());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "停止直播出错:" + result.getMsg());
                            if (result.getStatus() == Constant.TOKEN_INVALID) {
                                showToast(iv_liveRoomIdle, getString(R.string.login_expire));
                            }
                            return;
                        }
                        JSONObject data = (JSONObject) result.getData();
                        Log.d(TAG, "停止直播完成" + data.toJSONString());
                        notifyStopLive();
                        LiveRecord liveRecord = data.toJavaObject(LiveRecord.class);
                        liveRecord.setAudienceSize(accountList.size());
                        //补全id.从服务端传回的liveRecord 没有ID
                        String id = LiveAudienceActivity.this.liveRecord.getId();
                        liveRecord.setId(id);

                        if (liveRecord.getUserProfit() != null) {
                            StopLiveDialog stopLiveDialog = new StopLiveDialog(LiveAudienceActivity.this, liveRecord);
                            stopLiveDialog.setCanceledOnTouchOutside(false);
                            stopLiveDialog.show();
                        } else {
                            showToast(closeLive, "直播结束");
                        }
                        isAnchor = false;
                        isLiveStarted = false;
                        //mRtcEngine.muteLocalVideoStream(true);
                        //  setClientRole(Constants.CLIENT_ROLE_AUDIENCE);
                        removeVideoView();
                        stopLiveChangeUIForAnchor();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });
    }


    @OnClick(R.id.present_image)
    void onPresentImageClick() {
//        BottomPopupWindow popupWindow = new BottomPopupWindow(LiveAudienceActivity.this);
//        popupWindow.setItemText("1角", "5角", "1元", "5元", "10元", "100元");
//        popupWindow.showPopupWindow();
//        popupWindow.setItemClickListener(new BottomPopupWindow.onPopupWindowItemClickListener() {
//            @Override
//            public void onItemClick(int position) {
//                double money = 0;//单位 元
//                switch (position) {
//                    case 0:
//                        money = 0.1;
//                        break;
//                    case 1:
//                        money = 0.5;
//                        break;
//                    case 2:
//                        money = 1;
//                        break;
//                    case 3:
//                        money = 5;
//                        break;
//                    case 4:
//                        money = 10;
//                        break;
//                    case 5:
//                        money = 100;
//                        break;
//                }
//
//                reward(money);
//            }
//        });
        if (liveRecord == null || liveRoom == null) {
            return;
        }
        dialog = new PresentDialog(this, liveRecord, liveRoom.getId(), accountList.size(), this, presents);

        //设置颜色
      /*  View view1 = getLayoutInflater().inflate(R.layout.present_dialog_layout, null);
        dialog.setContentView(view1);
        try {
            // hack bg color of the BottomSheetDialog
            ViewGroup parent = (ViewGroup) view1.getParent();
            parent.setBackgroundResource(android.R.color.transparent);
        } catch (Exception e) {
            e.printStackTrace();
        }*/


        // dialog.setListener(this);
        dialog.show();

        // presentFragment.setOnFragmentInteractionListener(this);


    }


    @OnClick(R.id.iv_pass)
    void onPassImageClick() {
        // TODO: 2017/8/20 0020  喝倒彩 ，减少当前直播时长

//        BottomPopupWindow popupWindow = new BottomPopupWindow(LiveAudienceActivity.this);
//        popupWindow.setItemText("臭鸡蛋");
//        popupWindow.showPopupWindow();
//        popupWindow.setItemClickListener(new BottomPopupWindow.onPopupWindowItemClickListener() {
//            @Override
//            public void onItemClick(int position) {
//                Integer boo = -5;
//                reward(boo);
//            }
//        });
        final double money = 0.1;

        new PayUtils(money, LiveAudienceActivity.this, new PayUtils.InteractionListener() {
            @Override
            public void onPrepareComplete(String payPassword) {
                mulct(money, payPassword);
            }
        });


    }

    private void mulct(double money, String payPassword) {
        Mulct mulct = new Mulct();
        mulct.setAmount(money);
        mulct.setrId(liveRecord.getId());
        mulct.setlId(liveRoom.getId());
        mulct.setAudienceSize(accountList.size());
        Map<String, Object> body = new HashMap();
        body.put("mulct", mulct);
        body.put("payPassword", payPassword);

        RetrofitManager.getInstance().createRequest(LiveService.class)
                .mulct(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "点踩出错:" + response.code());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "点踩出错:" + result.getMsg());
                            switch (result.getStatus()) {
                                case Constant.TOKEN_INVALID:
                                    showToast(iv_pass, getString(R.string.login_expire));
                                    break;
                                case Constant.BALANCE_NOT_ENOUGH:
                                    showToast(iv_pass, getString(R.string.balance_not_enough_to_recharge));
                                    break;
                                case Constant.GET_LOCK_FAIL://打赏频率过高，并发了，这种可能太小，，
                                    showToast(iv_pass, getString(R.string.system_busy));
                            }
                            return;
                        }

                        JSONObject data = (JSONObject) result.getData();
                        Integer duration = data.getInteger("duration");
                        double balance = data.getDouble("balance");
                        myUserInfo.setBalance(balance);
                        UserProfileManager.getInstance().setUserBalance(balance);
                        Log.d(TAG, "点踩完成 余额：" + balance);
                        notifyMulct(mulct, duration);

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    /**
     * 检查余额是否足够，
     *
     * @param money
     * @return
     */
    private boolean isBalanceEnough(double money) {
        if (myUserInfo.getBalance() < money) {
            // TODO: 2018/8/14 应该弹出对话框，去充值，取消，，，
            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
            dialogBuilder.setTitle("提醒");
            dialogBuilder.setMessage(getString(R.string.balance_not_enough_to_recharge));
            dialogBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            dialogBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            dialogBuilder.create().show();
            //showToast(getString(R.string.balance_not_enough));
            return false;
        }
        return true;
    }

    @OnClick(R.id.iv_offer)
    void onOfferImageClick() {
//        OfferDialogNew offerDialogNew = new OfferDialogNew(this,dm.widthPixels);
//        offerDialogNew.show();

        OfferDialog offerDialog = OfferDialog.newInstance(100);
        offerDialog.show(getSupportFragmentManager(), "OfferDialog");
        offerDialog.setOnOfferClickListener(new OfferDialog.OnOfferClickListener() {
            @Override
            public void offerClick(final Integer offer) {
                Topic updateGoode = new Topic();
//                updateGoode.increment("auctionPrice", offer);
//                // TODO: 2016/11/9 0009 应该要判断结束时间是否是在5分钟之内，如果是，把结束时间 往后延迟5分钟，这些应该是在服务端判断 才科学哦？？？
//                updateGoode.update(bindGoods.getObjectId(), new UpdateListener() {
//                    @Override
//                    public void done(final BmobException e) {
//                        if (e == null) {
//                            maxOffer = maxOffer + offer;
//                            EMMessage message = EMMessage.createSendMessage(EMMessage.Type.CMD);
//                            message.setTo(chatroomId);
//                            EMCmdMessageBody cmdMessageBody = new EMCmdMessageBody(Constant.CMD_OFFER);
//                            message.addBody(cmdMessageBody);
//                            message.setAttribute("nick", DemoHelper.getInstance().getUserProfileManager().getUserNick());
//                            message.setAttribute("maxOffer", offer);
//                            message.setAttribute("avator", DemoHelper.getInstance().getUserProfileManager().getUserAvatar());
//                            message.setChatType(EMMessage.ChatType.ChatRoom);
//                            EMClient.getInstance().chatManager().sendMessage(message);
//                            showOffer(DemoHelper.getInstance().getUserProfileManager().getUserNick(), DemoHelper.getInstance().getUserProfileManager().getUserAvatar(), maxOffer + "");
//
//                        } else {
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    Toast.makeText(LiveAudienceActivity.this, "出价失败" + e.getContent(), Toast.LENGTH_LONG).show();
//                                }
//                            });
//                        }
//
//                    }
//                });
            }
        });
    }

    @Override
    public void onPresentSendSuccess(final Reward reward, Integer duration) {

        reward.setUser(myUserInfo);

        notifyReward(reward, duration);

        /**
         * 本地送出礼物不走服务端直接显示 启用此处需要同时修改LiveBaseActivity的
         *   initChannelListener()方法中的Constant.LIVE_ROOM_PUSH_MESSAGE_RECEIVED_REWARD情况
         */

        //showLeftGiftView(reward);
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {

//
//            }
//        });
    }

    @Override
    public void showToast(String message) {
        super.showToast(message);
    }

    /**
     * 进入直播间，查询直播间状态
     */
    private void queryLiveRoomStatus() {

        RetrofitManager.getInstance().createRequest(LiveService.class)
                .queryLiveRoom(liveRoom.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }

                        if (result.getData() == null) {
                            Log.e(TAG, "onResponse: 返回数据为空");
                            return;
                        }

                        JSONObject object = (JSONObject) result.getData();
                        JSONArray coupons = object.getJSONArray("coupons");
                        liveRoom = object.toJavaObject(LiveRoom.class);
                        if (coupons != null) {
                            List<Coupon> jcoupons = coupons.toJavaList(Coupon.class);
                            liveRoom.setCoupons(jcoupons);
                        }
                        Advertisement advertisement = liveRoom.getAdvertisement();
                        //Todo:判断coupon集合是不是空 如果空说明没红包
                        if (liveRoom.getCoupons() != null) {
                            couponList = liveRoom.getCoupons();
                        }
                        //进入直播间检测是否有红包

                        if (couponList != null && couponList.size() != 0) {
                            //如果进入直播间有红包
                            if (couponList.size() > 1) {
                                tv_red_Packet_Num.setText(couponList.size() + "");
                                tv_red_Packet_Num.setVisibility(View.VISIBLE);
                            }
                            Coupon coupon = couponList.get(0);
                            iv_redPacket.setVisibility(View.VISIBLE);
                            if (coupon.getStatus() == Constant.COUPON_STATUS_RECEIVED) {

                                iv_redPacket.setImageResource(R.drawable.tx_live_red_packet_open);
                            } else {
                                iv_redPacket.setAnimation(shakeAnimation(10));
                                iv_redPacket.setImageResource(R.drawable.tx_live_red_packet);

                            }
                        }
                        showAdvertisement(advertisement);
                        Integer status = liveRoom.getStatus();
                        if (status == null) {
                            return;
                        }
                        switch (status) {
                            case LIVE_ROOM_STATUS_STARTED:
                                getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                                anchor = liveRoom.getAnchor();
                                if (liveRoom.getLiveRecord() != null) {
                                    liveRecord = liveRoom.getLiveRecord();
                                    // countDownView.startCount(liveRecord.getDuration(), liveRecord.getCreated().getTime());
                                }
                                // rv_audienceList.showAnchorAvatar();
                                showRewardAndMulctView();
                                startLiveChangeUiForAudience();
                                hideLiveRoomIdleView();
                                if (anchor != null) {
                                    refreshGoodsList(anchor.getuId());
                                }
                                break;
                            case LIVE_ROOM_STATUS_STOPED:
                                stopLiveChangeUiForAudience();
                                break;

                            case LIVE_ROOM_STATUS_AUCTION:

                                getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                                //countDownView.startCount(liveRecord.getDuration(), liveRecord.getCreated().getTime());
                                anchor = liveRoom.getAnchor();
                                bindGoods = object.getObject("bindGoods", Topic.class);
                                changeUiForStartAuction();

                                for (int i = 0; i < audienceList.size(); i++) {
                                    String uId1 = audienceList.get(i).getUId();
                                    if (anchor.getUId().equals(uId1)) {
                                        User uanchor = audienceList.get(i);
                                        audienceList.remove(i);
                                        audienceList.add(0, uanchor);
                                    }

                                }

                                refreshGoodsList(anchor.getuId());
                                break;
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });

    }


    /**
     * 开启发送视频流
     */
    private void startLive() {
        isLiveStarted = true;
        // tv_countdownView.getAnimation().cancel();
        if (tv_countdownView.getVisibility() == View.VISIBLE) {
            tv_countdownView.setVisibility(View.GONE);
        }
        startBtn.setVisibility(View.GONE);
        bottomBar.setVisibility(View.VISIBLE);
        //发送本地视频流
        // mRtcEngine.muteLocalAudioStream(false);
        //mRtcEngine.muteLocalVideoStream(false);
    }

    /**
     * 开始直播，主播端调整UI
     */
    private void startLiveChangeUIForAnchor() {
        //判断输入框是否是显示状态，如果是，则隐藏，因为进入主播状态后，用的着输入框的可能比较小
        if (messageView.isInputViewDisplay()) {
            messageView.setShowInputView(false);
        } else {
            bottomBar.setVisibility(View.GONE);
        }
        iv_liveRoomIdle.setVisibility(View.GONE);
        coverView.setVisibility(View.GONE);
        startBtn.setVisibility(View.VISIBLE);
        iv_lightSwitch.setVisibility(View.VISIBLE);
        iv_voiceSwitch.setVisibility(View.VISIBLE);
        if (iv_voiceSwitch.isSelected()) {
            iv_voiceSwitch.setSelected(false);
        }
        iv_cameraSwitch.setVisibility(View.VISIBLE);
        iv_redPacket.setVisibility(View.VISIBLE);
        setMessageViewLayoutToSmall();
    }

    /**
     * 停止直播，主播端调整UI
     */
    private void stopLiveChangeUIForAnchor() {
        if (messageView.isInputViewDisplay()) {
            messageView.setShowInputView(false);
        }
        iv_liveRoomIdle.setVisibility(View.VISIBLE);
        coverView.setVisibility(View.VISIBLE);
        iv_lightSwitch.setVisibility(View.GONE);
        iv_voiceSwitch.setVisibility(View.GONE);
        iv_cameraSwitch.setVisibility(View.GONE);
        if (startBtn.isShown()) {
            startBtn.setVisibility(View.GONE);
        }
        if (!bottomBar.isShown()) {
            bottomBar.setVisibility(View.VISIBLE);
        }
        if (tv_countdownView.isShown()) {
            tv_countdownView.setVisibility(View.INVISIBLE);
        }
        setMessageViewLayoutToBig();
    }

    /**
     * 开始直播的时候，让MessageView 变小，不要挡住直播画面
     */
    private void setMessageViewLayoutToSmall() {
        RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, (int) (msgViewHeight * dm.density));
        param.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        messageView.setLayoutParams(param);
    }

    /**
     * 没有直播的时候，让MessageView 变大，能显示更多观众发的信息
     */
    private void setMessageViewLayoutToBig() {
        RelativeLayout.LayoutParams param2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        param2.addRule(RelativeLayout.BELOW, R.id.toolbar);
        messageView.setLayoutParams(param2);
    }

    /**
     * 打赏
     *
     * @param money
     */
    private void reward(final double money) {
        //先检查用户余额
        if (!isBalanceEnough(money)) return;
        Reward reward = new Reward();
        reward.setrId(liveRecord.getId());
        reward.setAmount(money);
        RetrofitManager.getInstance().createRequest(LiveService.class)
                .reward(reward)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "打赏出错:" + response.code());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "打赏出错:" + result.getMsg());
                            switch (result.getStatus()) {
                                case Constant.TOKEN_INVALID:
                                    showToast(iv_liveRoomIdle, getString(R.string.login_expire));
                                    break;
                                case Constant.BALANCE_NOT_ENOUGH:
                                    showToast(iv_liveRoomIdle, getString(R.string.balance_not_enough));
                                    break;
                                case Constant.GET_LOCK_FAIL://打赏频率过高，并发了，这种可能太小，，
                                    showToast(iv_liveRoomIdle, getString(R.string.system_busy));

                            }
                            return;
                        }
                        Log.d(TAG, "打赏完成");

                        //对个人总金额进行扣除操作
                        myUserInfo.setBalance(myUserInfo.getBalance() - money);
                        UserProfileManager.getInstance().syncLoginUserInfo(myUserInfo);

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        t.printStackTrace();
                        Log.e(TAG, "打赏出错:" + t.getMessage());

                    }
                });

    }

    private void readyLiveChangeUiForAudience() {
        //如果在软键盘打开的情况下，显示远程视频view,view 会被缩小，只有隐藏掉软件盘
        if (messageView.isInputViewDisplay()) {
            messageView.setShowInputView(false);
            bottomBar.setVisibility(View.VISIBLE);
        }
        // hideLiveRoomIdleView();
    }

    private void hideLiveRoomIdleView() {
        if (iv_liveRoomIdle.isShown()) {
            iv_liveRoomIdle.setVisibility(View.GONE);
        }
    }

    /**
     * 开始直播，观众端调整ui
     */
    private void startLiveChangeUiForAudience() {


        iv_offer.setVisibility(View.GONE);
        coverView.setVisibility(View.GONE);
        setMessageViewLayoutToSmall();
    }

    private void showRewardAndMulctView() {
        iv_present.setVisibility(View.VISIBLE);
        iv_pass.setVisibility(View.VISIBLE);
    }

    /**
     * 停止直播，观众端调整UI
     */
    private void stopLiveChangeUiForAudience() {
        iv_offer.setVisibility(View.GONE);
        iv_present.setVisibility(View.GONE);
        iv_pass.setVisibility(View.GONE);
        tv_bindGoodsName.setVisibility(View.INVISIBLE);

        offerView.setVisibility(View.INVISIBLE);
        tv_offerAmount.setVisibility(View.INVISIBLE);
        countDownView.stopCount();
        goodsAdapter.notifyDataSetChanged();
        iv_liveRoomIdle.setVisibility(View.VISIBLE);
        coverView.setVisibility(View.VISIBLE);
        setMessageViewLayoutToBig();
        //停止直播的时候情况掉打赏和出价的列表，避免出现直播停止了，还一直在显示上一场直播观众的打赏和出价
        rewardList.clear();
        ordersList.clear();
        if (dialog != null) {
            dialog.dismiss();


        }


    }

    /**
     * 进入拍卖状态，调整UI
     */
    private void changeUiForStartAuction() {
        if (!isLiveStarted) {
            if (anchor != null) {
                //  rv_audienceList.showAnchorAvatar();
            }
            iv_liveRoomIdle.setVisibility(View.GONE);

        }
        tv_bindGoodsName.setText(bindGoods.getTitle());
        iv_offer.setVisibility(View.VISIBLE);
        tv_bindGoodsName.setVisibility(View.VISIBLE);
        setMessageViewLayoutToSmall();
    }

    public void handleUpdateCountdown() {
        if (tv_countdownView != null) {
            tv_countdownView.setVisibility(View.VISIBLE);
            tv_countdownView.setText(String.format("%d", countDown));

            ScaleAnimation scaleAnimation =
                    new ScaleAnimation(1.0f, 0f, 1.0f, 0f, Animation.RELATIVE_TO_SELF, 0.5f,
                            Animation.RELATIVE_TO_SELF, 0.5f);
            scaleAnimation.setDuration(COUNTDOWN_DELAY);
            scaleAnimation.setFillAfter(false);
            scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    tv_countdownView.setVisibility(View.GONE);
                    //startBtn.setVisibility(View.GONE);

//                    if (count == COUNTDOWN_END_INDEX) {
//                        // showToast(startBtn, "自动退出直播");
//                        //close();
//                        //倒计时结束，自动开启推流，避免一直占用着直播间，观众端又看不到画面
//                        if (!isLiveStarted) {
//                            runOnUiThread(() -> startLive());
//                        }
//                    }
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            tv_countdownView.startAnimation(scaleAnimation);

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isMessageListInited)
            messageView.refresh();
        //  EaseUI.getInstance().pushActivity(this);
        // register the event listener when enter the foreground

//        if (realTimeData.isConnected()) {
//            realTimeData.subRowUpdate("LiveRoom", liveRoom.getObjectId());
//        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        //mVideoView.onPause();
//        if (realTimeData.isConnected()) {
//            realTimeData.unsubRowUpdate("LiveRoom", liveRoom.getObjectId());
//        }
    }

    @Override
    public void onStop() {
        super.onStop();
        // unregister this event listener when this activity enters the
        // background


        // 把此activity 从foreground activity 列表里移除
        //  EaseUI.getInstance().popActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // mRtcEngine.leaveChannel();
        //  RtcEngine.destroy();
    }

    @Override
    public void onBackPressed() {
        if (!isAnchor) {
            super.onBackPressed();
            return;
        }
        AlertDialog.Builder dialogBuild = new AlertDialog.Builder(this);
        dialogBuild.setTitle("提醒");
        dialogBuild.setMessage("正在直播中，确定退出吗？");
        dialogBuild.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                close();
            }
        });
        dialogBuild.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialogBuild.create().show();

    }

    @Override
    public void onTimeOut() {
        if (isAnchor) {
            stopLiveToService();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        if (requestCode == REQUEST_CODE_OFFER) {
            Orders updateOrders = data.getParcelableExtra("offer");
            tv_advertisementPrice.setText("当前价：￥" + Utils.numberFormat(updateOrders.getAmount()));

        }
    }

}
